<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: ical.php 1126 2008-06-09 05:45:04Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *    
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

  /**
   * get the games for the specified project / rounds / division
   *
   * @param object the project
   * @param int round matchcode
   * @param int division id (if 0, whole project)
   * @ordering string
   * @ordering bool display unpublished ?              
   */
  function getProjectGames( $project, $divisionId = 0, $teamId = 0, $unpublished = 0 )
  {    
	  /**
	   * get divisions
	   */  	  	  
	  if ($divisionId > 0) 
    {
	    $div_for_teams = array( $divisionId );
      $query = "SELECT id FROM #__joomleague_divisions WHERE parent_id = $divisionId";
	    $project->_db->setquery($query);
	    $div_for_teams = array_merge( $div_for_teams, $project->_db->loadResultArray() );
	  }
    
    $result = array();
    
    // build query
    $query = " SELECT matches.*,
                      t1.name AS homeName,
                      t2.name AS awayName,
                      r.name as roundName,
                      p.name AS playgroundName, p.address AS address, p.zip AS zip, p.city AS city ";
    // get referee id and name
    if ( $project->teams_as_referees ) {
      $query .= ", ref.id as refereeId, ref.name AS refereeName";
    }
    else {
      $query .= ", ref.id as refereeId, CONCAT( ref.firstname, ' ', ref.lastname ) AS refereeName ";    
    }    
    
    $query .= " FROM #__joomleague_matches AS matches
               INNER JOIN #__joomleague_rounds AS r ON r.id = matches.round_id
               INNER JOIN #__joomleague_teams AS t1 ON t1.id = matches.matchpart1 
               INNER JOIN #__joomleague_teams AS t2 ON t2.id = matches.matchpart2 
               LEFT  JOIN #__joomleague_playgrounds AS p ON p.id = matches.playground_id ";
    if ( $project->teams_as_referees ) {
      $query .= "LEFT JOIN #__joomleague_teams AS ref ON ref.id = matches.referee_id ";
    }
    else {
      $query .= "LEFT JOIN #__joomleague_referees AS ref ON ref.id = matches.referee_id ";   
    }
    if ( $divisionId > 0 ) {
      $query .= " INNER JOIN #__joomleague_team_joomleague AS tt1 ON ( matches.matchpart1 = tt1.team_id AND matches.project_id = tt1.project_id )
                  INNER JOIN #__joomleague_team_joomleague AS tt2 ON ( matches.matchpart2 = tt2.team_id AND matches.project_id = tt2.project_id ) ";
    }
    
    $query .= " WHERE  matches.project_id = ".$project->id;    
    if ( $teamId ) {
    	$query .= " AND ( t1.id = $teamId OR t2.id = $teamId ) ";
    }    
    if ($unpublished!=1) {
      $query .= " AND matches.published = 1 ";
    }
    
    if ( $divisionId > 0 ) {
      $query .= " AND ( tt1.division_id IN ( " . implode( ',', $div_for_teams ) . " ) 
                     OR tt2.division_id IN ( " . implode( ',', $div_for_teams ) . " ) )";                      
    }
    
    $query .= " ORDER BY matches.match_date ASC, matches.match_number";
    $project->_db->setQuery($query);
    //print $project->_db->getQuery(); exit;
    $result = $project->_db->loadObjectList();

    return $result;
  }
  
function manageIcal()
{ 
  global $my, $mainframe, $database;
  global $joomleague, $jlgConfig, $htmlHelper, $no_html;
  
  $no_html=1;
  
  $type = strtolower( mosGetParam( $_REQUEST, '$type', '') );
  
  $divisionId = intval( mosGetParam( $_REQUEST, 'division', 0) );
  $teamId = intval( mosGetParam( $_REQUEST, 'tid', 0) );
  
  switch ( $type )
  {
  	case team: //calendar for given team in all published projects
  		
  		break;
  	
    case teamref: //calendar for given team as a ref in all published projects
      
      break;
  	case project:
  	default:
		  $games = getProjectGames( $joomleague, $divisionId, $teamId );
		  $output  = "BEGIN:VCALENDAR\n";
		  $output .= "VERSION:2.0\n";
		  $output .= "PRODID:-//" . $mainframe->getCfg('sitename') . "//NONSGML v1.0//EN\n";
			
		  foreach ( $games as $game )
		  {    
		    if ( $game->match_date && ereg( "([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})", $game->match_date, $regs ) ) 
		    {
		      $date = mktime( $regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1] );
		      if ( $date > -1 ) 
		      {        
		        $output .= "BEGIN:VEVENT\n";
		        
		        // fields DTSTART and DTEND
		        $startdate = strftime( '%Y%m%dT%H%M%S', $date );
		        $enddate = strftime( '%Y%m%dT%H%M%S', $date + $joomleague->game_regular_time*60 );
		        $output .= "DTSTART:$startdate\n";
		        $output .= "DTEND:$enddate\n";
		        
		        // field SUMMARY
		        $output .= "SUMMARY:" 
		                . $joomleague->name . " - " . $game->roundName . ": "
		                . $game->homeName." - ".$game->awayName."\n";
		                
		        // field DESCRIPTION
		        $output .= "DESCRIPTION:";
		        if ( $game->refereeId ) {
		           $output .= _JL_PLAN_REFEREE . ": " . $game->refereeName."\\n"; 
		        }
		        $output .= "\n";
		        
		        // field LOCATION
		        if ( $game->playgroundName != null ) {
		          $output .= "LOCATION:$game->playgroundName";
		          if ($game->address || $game->city || $game->zip) {
		            $output .= ' - ';
		            if ($game->address) {
  		            $output .= $game->address;
  		          }
                if ($game->city) {
                  if ($game->address) {
                    $output .= ', ';
                  }
                  $output .= $game->city;
                  if ($game->zip) {
                    $output .= ', ' . $game->zip;
                  }
                }
  		        }
		          $output .= "\n";
		        }
		        
		        $output .= "END:VEVENT\n";
		      }
		    }
		  }
		  $output .= "END:VCALENDAR\n";
		  // Define the file as an iCalendar file
		  header("Content-Type: text/Calendar");
		  // Give the file a name and force download
		  header("Content-Disposition: inline; filename=calendar.ics");
		  echo utf8_encode($output);
		            
		  exit; // a bit brutal, but we don't need more display !!*/
		  break; // not really usefull...
  }
  return true;
}
?>